package com.learning.optimize.jdk.proxy.aop;

import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * ClassName: AopMain
 * Description:
 * Date: 2018/7/25 9:27 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class AopMain {

    public static void main(String[] args) {
        test();
    }


    static void test() {
        Target target = new CustomTarget();
        Advice advice = new CustomAdvice();
        CustomInvocationHandler invocationHandler = new CustomInvocationHandler(advice, target);

        Target proxy = (Target) ProxyUtil.getProxy(target, invocationHandler);
        proxy.first();

        /*
            输出：
            在什么时候被调用
            ~~~ 在方法调用之前 ~~~
            方法 first 被调用了
            ~~~ 方法已经调用结束啦 ~~~
            first 方法一共运行的时间为 1
        */
    }

}

@Setter
@Getter
class CustomInvocationHandler implements InvocationHandler {

    /**
     * 切面对象
     */
    private Advice advice;
    /**
     * 被代理对象，即目标属性
     */
    private Object target;


    public CustomInvocationHandler(Advice advice, Object target) {
        this.advice = advice;
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        advice.before(method);

        Object obj = method.invoke(target, args);

        advice.after(method);

        return obj;
    }
}
